import java.util.NoSuchElementException;

/**
 * Created with IntelliJ IDEA.
 * User: Batiuk
 * Date: 06.12.13
 * Time: 16:08
 * To change this template use File | Settings | File Templates.
 */
public class LinkedListQueue<E> implements IQueue<E> {

	private Node posOfHead;
	private Node posOfTail;

	@Override
	public boolean offer(E element) {
		if ( element == null ) {
			throw new NullPointerException();
		}
		if ( posOfHead == null ) {
			posOfHead = posOfTail = new Node(null, element, null);
		} else {
			posOfTail.nextLink = new Node(posOfTail, element, null);
			posOfTail = posOfTail.nextLink;
		}
		return true;
	}


	@Override
	public E element() {
		E result = peek();
		if ( result == null ) {
			throw new NoSuchElementException();
		}
		return result;
	}


	@Override
	public E peek() {
		if ( posOfHead != null ) {
			return posOfHead.element;
		} else {
			return null;
		}
	}

	@Override
	public E poll() {
		if ( posOfHead != null ) {
			E result = posOfHead.element;
			posOfHead = posOfHead.nextLink;
			return result;
		}
		return null;
	}

	@Override
	public E remove() {
		E result = poll();
		if ( result == null ) {
			throw new NoSuchElementException();
		}
		return result;
	}


	private class Node {
		private Node prevLink;
		private Node nextLink;
		private E element;

		public Node(Node prevLink, E element, Node nextLink) {
			this.prevLink = prevLink;
			this.nextLink = nextLink;
			this.element = element;
		}

		public Node() {

		}
	}

}
